package com.test.qnews.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.test.qnews.R;
import com.test.qnews.Recommend;
import com.test.qnews.RecommendDao;
import com.test.qnews.activity.DetailsActivity;
import com.test.qnews.adapter.CommonAdapter;
import com.test.qnews.adapter.ViewPagerAdapter;
import com.test.qnews.beans.GsonBean;
import com.test.qnews.beans.NetDataBean;
import com.test.qnews.custom.RefreshableView;
import com.test.qnews.db.DaoSingleton;
import com.test.qnews.volley.VolleySingleton;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import de.greenrobot.dao.query.Query;

/**
 * Created by dllo on 16/1/8.
 */
public class RecommendFragment extends Fragment {
    private ListView listView;
    private Context context;

    private CommonAdapter commonAdapter;


    private ViewPagerAdapter viewPagerAdapter;
    private ViewPager viewPager;
    private int item = 2;
    private TextView textView;
    private List<View> listViews;
    private int[] imgs = {R.mipmap.wel, R.mipmap.error,
            R.mipmap.wel, R.mipmap.wel};

    private List<NetDataBean> data;
    private String url = "http://zzd.sm.cn/appservice/api/v1/channel/100?client_os=android&" +
            "client_version=2.1.0.1&bid=800&m_ch=008&city=0837&sn=97e463a2a58aa490289f6c346" +
            "be4dec0&content_cnt=20&recoid=1723305677815724895&ftime=1452069819162&method=new&count=20";

    //数据库
    private List<Recommend> recommends = new ArrayList<>();
    private RecommendDao recommendDao = DaoSingleton.getInstance().getRecommendDao();

    //刷新
    RefreshableView refreshableView;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_recommend, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        refreshableView = (RefreshableView) view.findViewById(R.id.refreshable_view);
        listView = (ListView) view.findViewById(R.id.lv_recommend);
        //轮播视图
        listViews = new ArrayList<>();
        View headView = LayoutInflater.from(context).inflate(R.layout.viewpager_head, null);
        viewPager = (ViewPager) headView.findViewById(R.id.headviewpager);
        for (int i = 0; i < imgs.length; i++) {
            View view1 = LayoutInflater.from(context).inflate(R.layout.item_head_viewpager, null);
            ImageView iv = (ImageView) view1.findViewById(R.id.item_head);
            textView = (TextView) view1.findViewById(R.id.item_head_tv);
            textView.setText((i + 1) + "/" + imgs.length);
            iv.setImageResource(imgs[i]);
            listViews.add(view1);
        }

        viewPagerAdapter = new ViewPagerAdapter(context, listViews);
        viewPager.setAdapter(viewPagerAdapter);

        listView.addHeaderView(headView);

//        viewPager.setCurrentItem(Integer.MAX_VALUE / 2);//默认在中间，使用户看不到边界


//调用刷新的方法
//        refreshableView.setOnRefreshListener(new RefreshableView.PullToRefreshListener() {
//            @Override
//            public void onRefresh() {
//                data();
//                try {
//                    Thread.sleep(2000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//                refreshableView.finishRefreshing();
//            }
//        }, 0);
//
////listView里的数据
        data();

    }

    public void data() {
//        VolleySingleton.getInstance();
        VolleySingleton.getInstance().addRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                Gson gson = new Gson();
                data = new ArrayList<>();
                GsonBean gsonBean = gson.fromJson(response, GsonBean.class);

                for (int i = 0; i < gsonBean.getData().getArticle().size(); i++) {
                    NetDataBean netDataBean = new NetDataBean();
                    netDataBean.setSource_name(gsonBean.getData().getArticle().get(i).getSource_name());
                    netDataBean.setContent(gsonBean.getData().getArticle().get(i).getContent());
                    netDataBean.setTitle(gsonBean.getData().getArticle().get(i).getTitle());
//                    netDataBean.setTime(gsonBean.getData().getArticle().get(i).getComment_cnt());
                    netDataBean.setItem_type(gsonBean.getData().getArticle().get(i).getItem_type());
                    netDataBean.setContent(gsonBean.getData().getArticle().get(i).getContent());
                    for (int j = 0; j < gsonBean.getData().getArticle().get(i).getImage().size(); j++) {

                        netDataBean.setImageUrl(gsonBean.getData().getArticle().get(i).getImage().get(0).getUrl());
                    }
                    data.add(netDataBean);

                    /**
                     * 每次再有网的情况下运行,会删除数据库中的数据
                     */
                    clearAll();

                    /**
                     * 添加到数据库
                     */
                    Recommend recommend = new Recommend();
                    recommend.setTitle(data.get(i).getTitle());
                    recommend.setContent(data.get(i).getContent());
                    recommend.setImageUrl(data.get(i).getImageUrl());
                    recommend.setItem_type(data.get(i).getItem_type());

                    recommends.add(recommend);

                    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            Intent intent = new Intent(getActivity(), DetailsActivity.class);
                            intent.putExtra("pos", position - 1);
                            intent.putExtra("data", (Serializable) data);
                            startActivity(intent);
                        }
                    });
                }


                recommendDao.insertInTx(recommends);

                commonAdapter = new CommonAdapter(data, context);
                listView.setAdapter(commonAdapter);

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
//                search();
                commonAdapter = new CommonAdapter(context, search());
                listView.setAdapter(commonAdapter);
                listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        Toast.makeText(context, "没联网,是不是傻!", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    //db查询
    private List<Recommend> search() {
        if (recommendDao != null) {
            return recommendDao.queryBuilder().list();
        } else {
            return null;
        }
    }

    //db删除
    public void clearAll() {
        if (recommendDao != null) {
            recommendDao.deleteAll();
        }
    }

}
